class ActivitiesController < InnerApplicationController
  
  # GET /activities
  # GET /activities.xml
  def index
    @activities = @project.activities.all(:include => [:project, :milestone, :comments])
    
    @open = @project.activities.open
    @completed = @project.activities.completed
    @recent = @project.activities.recent
  end

  # GET /activities/1
  # GET /activities/1.xml
  def show
    @activity = @project.activities.find(params[:id])
    @comment = @activity.comments.new
  end

  # GET /activities/new
  # GET /activities/new.xml
  def new
    @activity = @project.activities.new
  end

  # GET /activities/1/edit
  def edit
    @activity = @project.activities.find(params[:id])
  end

  # POST /activities
  # POST /activities.xml
  def create
    @activity = @project.activities.new(params[:activity])
    
    if @activity.save
      redirect_to project_activities_url# @project, @activity
    else
      render :action => "new"
    end
  end

  # PUT /activities/1
  # PUT /activities/1.xml
  def update
    @activity = @project.activities.find(params[:id])
    
    if params[:activity][:completed_at] == 1.to_s
      params[:activity][:completed_at] = Time.now
    else
      params[:activity][:completed_at] = nil
    end
    
    if @activity.update_attributes(params[:activity])
      
      @comment = @activity.comments.new(params[:comment])
      @comment.author = current_user
      @comment.save
      
      flash[:success] = 'Activity was successfully updated.'
      redirect_to @activity
    else
      render :action => "edit"
    end
  end

  # DELETE /activities/1
  # DELETE /activities/1.xml
  def destroy
    @activity = @project.activities.find(params[:id])
    @activity.destroy

    respond_to do |format|
      format.html { redirect_to(activities_url) }
      format.xml  { head :ok }
    end
  end
end
